﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Example.WebAPI
{
    public class GlobalException : IAsyncExceptionFilter
    {
        private readonly ILogger<GlobalException> logger;
        private readonly IHostEnvironment hostEnvironment;

        public GlobalException(ILogger<GlobalException> logger, IHostEnvironment hostEnvironment)
        {
            this.logger = logger;
            this.hostEnvironment = hostEnvironment;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!hostEnvironment.IsDevelopment())
            {
                //没处理的我们统一处理
                if (!context.ExceptionHandled)
                {
                    logger.LogError(context.Exception, context.Exception.Message);
                    context.Result = new ContentResult
                    {
                        Content = "服务器繁忙。。。",
                    };
                }

                //标注已处理
                context.ExceptionHandled = true;
                return Task.CompletedTask;
            }
            
            context.Result = new ContentResult
            {
                Content = context.Exception.ToString()
            };

            return Task.CompletedTask;
        }
    }
}
